<template>
	<div class="component-upload-image">
		<el-checkbox-group
			v-show="false"
			v-model="fileList"></el-checkbox-group>
		<el-upload
			multiple
			:accept="accept"
			:disabled="disabled"
			:action="uploadImgUrl"
			list-type="picture-card"
			:on-success="handleUploadSuccess"
			:before-upload="handleBeforeUpload"
			:on-change="handleChange"
			:limit="limit"
			:on-error="handleUploadError"
			:on-exceed="handleExceed"
			ref="imageUpload"
			:on-remove="handleDelete"
			:show-file-list="true"
			:headers="headers"
			:file-list="fileList"
			:on-preview="handlePictureCardPreview"
			:class="{
				hide: this.fileList.length >= this.limit,
				uoloadSty: showBtnDealImg,
				disUoloadSty: noneBtnImg,
				hideRight: disabled,
			}">
			<i class="el-icon-plus">
				<span
					style="
						display: block;
						color: #0084ff;
						font-size: 12px;
						position: relative;
						top: 12px;
					">
					{{ info }}
				</span>
			</i>

			<div class="file-wrap" slot="file" slot-scope="{ file }">
				<div
					class="flex-colum-center file-name"
					v-if="isFile(file.url)">
					<img
						style="width: 24px; height: 24px"
						src="../../assets/images/file_word.png" />
					<span class="file-name_inline">{{ file.fileName }}</span>
				</div>

				<!-- <el-image -->
				<!-- v-else -->
				<!-- style="width: 100%; height: 100%" -->
				<!-- :src="file.url" -->
				<!-- :preview-src-list="srcList"></el-image> -->
				<img
					v-else
					class="el-upload-list__item-thumbnail"
					:src="file.url"
					alt=""
					@click="enlargeImage(file.url)" />
				<!-- v-if="ifImage(file.url)" -->
				<span class="el-upload-list__item-actions">
					<span
						v-if="canOpen(file)"
						class="el-upload-list__item-preview"
						@click="handlePictureCardPreview(file)">
						<i class="el-icon-zoom-in"></i>
					</span>
					<span
						class="el-upload-list__item-delete"
						@click="handleDownload(file)">
						<i class="el-icon-download"></i>
					</span>
					<span
						v-if="!disabled"
						class="el-upload-list__item-delete"
						@click="handleDelete(file, fileList)">
						<i class="el-icon-delete"></i>
					</span>
				</span>
			</div>
		</el-upload>
		<span
			v-if="
				disabled &&
				(fileList === undefined ||
					fileList === null ||
					fileList == '' ||
					fileList == [])
			">
			--
		</span>

		<!-- 上传提示 -->
		<div class="el-upload__tip" slot="tip" v-if="showTip">
			<template v-if="fileSize">
				请上传大小不超过
				<b style="color: #f56c6c">{{ fileSize }}MB</b>
			</template>
			<template v-if="fileType">
				格式为
				<b style="color: #f56c6c">{{ fileType.join('/') }}</b>
				的文件,
			</template>
			<template v-if="fileType">
				最多
				<b style="color: #f56c6c">{{ limit }}份</b>
			</template>
		</div>

		<el-dialog
			:visible.sync="dialogVisible"
			width="70%"
			append-to-body
			title="预览">
			<template v-if="isFile(dialogImageUrl)">
				<el-input
					v-if="isTxt"
					:autosize="{ minRows: 8, maxRows: 15 }"
					v-model="txtContent"
					placeholder=""
					readonly
					type="textarea"></el-input>

				<vue-office-docx
					v-else-if="isDoc"
					:src="dialogImageUrl"
					style="height: 100vh" />

				<vue-office-excel
					v-else-if="isExcel"
					:src="dialogImageUrl"
					style="height: 100vh" />

				<iframe
					v-else
					:src="dialogImageUrl"
					frameborder="1"
					width="100%"
					height="600">
					<head>
						<meta
							http-equiv="Content-Type"
							content="text/html; charset=UTF-8" />
					</head>
				</iframe>
			</template>
			<el-image
				v-else
				style="width: 100%"
				:src="dialogImageUrl"
				:preview-src-list="srcList"></el-image>
			<!-- <img
                v-else
                :src="dialogImageUrl"
                style="display: block; max-width: 100%; margin: 0 auto"
            /> -->
		</el-dialog>
	</div>
</template>

<script>
	import preview from '@/components/A/previewDialog/preview.js';
	import { getToken } from '@/utils/auth';
	import { listByIds, delOss, downFile } from '@/api/system/oss';
	//引入VueOfficeDocx组件
	import VueOfficeDocx from '@vue-office/docx';
	//引入相关样式
	import '@vue-office/docx/lib/index.css';
	//引入VueOfficeExcel组件
	import VueOfficeExcel from '@vue-office/excel';
	//引入相关样式
	import '@vue-office/excel/lib/index.css';

	export default {
		components: {
			VueOfficeDocx,
			VueOfficeExcel,
		},
		props: {
			upType: {
				type: Number,
				default: 0, //0图片 1文件  2图片+文件
			},
			info: {
				type: String,
				default: '请选择',
			},
			value: {
				type: [String, Object, Array],
				default: () => {
					return [];
				},
			},
			// 图片数量限制
			limit: {
				type: Number,
				default: 20,
			},
			// 大小限制(MB)
			fileSize: {
				type: Number,
				default: 50,
			},
			// 文件类型, 例如['png', 'jpg', 'jpeg']
			fileType: {
				type: Array,
				default: () => ['png', 'jpg', 'jpeg'],
			},
			// 是否显示提示
			isShowTip: {
				type: Boolean,
				default: false,
			},
			disabled: {
				type: Boolean,
				default: false,
			},
		},
		data() {
			return {
				showBtnDealImg: true,
				noneBtnImg: false,
				number: 0,
				uploadList: [],
				dialogImageUrl: '',
				dialogVisible: false,
				hideUpload: false,
				// baseFileUrl: 'http://view.xdocin.com/xdoc?_xdoc=',
				baseFileUrl:
					'https://view.officeapps.live.com/op/view.aspx?src=',
				baseUrl: process.env.VUE_APP_BASE_API,
				uploadImgUrl:
					process.env.VUE_APP_BASE_API + '/system/oss/upload', // 上传的图片服务器地址
				headers: {
					Authorization: 'Bearer ' + getToken(),
				},
				fileList: [],
				img: '.png, .jpg, .jpeg, .bmp, .gif, .webp, .psd, .svg, .tiff',
				// .doc, doc文件预览不了，所以暂时去掉
				file: '.docx, .xls, .xlsx, .ppt, .pptx, .txt, .pdf, .csv, .ftr, .mov, .mp4, .msg, .zip, .tar, .rar, .7z',
				unKnowFile: '.csv, .ftr, .mov, .mp4, .msg, .ppt, .pptx', //不支持预览的文件类型
				txtContent: '',
				isTxt: false,
				isDoc: false,
				isExcel: false,
				srcList: [],
			};
		},
		watch: {
			value: {
				async handler(val) {
					if (val) {
						// 首先将值转为数组
						let list;
						if (Array.isArray(val)) {
							list = val;
						} else {
							await listByIds(val).then(res => {
								list = res.data;
							});
						}

						// 然后将数组转为对象数组
						this.fileList = list.map(item => {
							// 此处name使用ossId 防止删除出现重名
							item = {
								name: item.ossId,
								url: item.url,
								ossId: item.ossId,
								fileName: item.originalName,
							};
							this.srcList.push(item.url);
							return item;
						});

						this.noneBtnImg =
							this.disabled || this.fileList.length >= this.limit;
					} else {
						this.fileList = [];
						this.noneBtnImg =
							this.disabled || this.fileList.length >= this.limit;
						return [];
					}
				},
				deep: true,
				immediate: true,
			},
		},
		computed: {
			// 是否显示提示
			showTip() {
				return this.isShowTip && (this.fileType || this.fileSize);
			},
			accept() {
				const all = this.img + ', ' + this.file;

				return this.upType == 2
					? all
					: this.upType == 1
					? this.file
					: this.img;
			},
		},
		methods: {
			ifImage(url) {
				let fileExtension = url.slice(url.lastIndexOf('.') + 1);
				if (fileExtension == 'jpg' || fileExtension == 'png') {
					return false;
				} else {
					return true;
				}
				console.log(fileExtension, 1111111);
			},
			isFile(url) {
				let fileExtension = url.slice(url.lastIndexOf('.') + 1);
				return this.file.indexOf(fileExtension) >= 0;
			},
			handleChange(file, fileList) {
				this.noneBtnImg =
					this.disabled || fileList.length >= this.limit;
			},
			// 上传前loading加载
			handleBeforeUpload(file) {
				if (this.disabled) {
					return;
				}

				// let isImg = false;
				// if (this.fileType.length) {
				//     let fileExtension = "";
				//     if (file.name.lastIndexOf(".") > -1) {
				//         fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
				//     }
				//     isImg = this.fileType.some((type) => {
				//         if (file.type.indexOf(type) > -1) return true;
				//         if (fileExtension && fileExtension.indexOf(type) > -1) return true;
				//         return false;
				//     });
				// } else {
				//     isImg = file.type.indexOf("image") > -1;
				// }
				//
				// if (!isImg) {
				//     this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
				//     return false;
				// }
				const fileName = file.name.split('.');
				const fileExt = fileName[fileName.length - 1];
				// 校检文件类型
				let acceptArr = this.accept.split(',');
				let accept = `.${fileExt}`;
				if (this.accept) {
					let index = acceptArr.findIndex(e => e.trim() == accept);
					if (index == -1) {
						this.$message({
							type: 'error',
							message: `文件格式不正确, 请上传${this.accept}格式文件!`,
						});
						return false;
					}
				}
				if (this.fileSize) {
					const isLt = file.size / 1024 / 1024 < this.fileSize;
					if (!isLt) {
						this.$modal.msgError(
							`大小不能超过 ${this.fileSize} MB!`,
						);
						return false;
					}
				}
				this.$modal.loading('正在上传，请稍候...');
				this.number++;
			},
			// 文件个数超出
			handleExceed() {
				this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
			},
			// 上传成功回调
			handleUploadSuccess(res, file) {
				this.$modal.closeLoading();
				if (res.code === 200) {
					this.uploadList.push({
						name: res.data.fileName,
						url: res.data.url,
						ossId: res.data.ossId,
					});
					this.uploadedSuccessfully();
				} else {
					this.number--;

					this.$modal.msgError(res.msg);
					this.$refs.imageUpload.handleRemove(file);
					this.uploadedSuccessfully();
				}
				this.$emit('uploadEnd', 'success');
			},
			handleDownload(file) {
				console.log('文件---', file);
				this.$download.oss(file.ossId);
			},
			// 删除图片
			handleDelete(file, fileList) {
				this.noneBtnImg =
					this.disabled || fileList.length >= this.limit;
				const findex = this.fileList
					.map(f => f.name)
					.indexOf(file.name);
				if (findex > -1) {
					let ossId = this.fileList[findex].ossId;
					delOss(ossId);
					this.fileList.splice(findex, 1);
					this.$emit('input', this.listToString(this.fileList));
				}
			},
			// 上传失败
			handleUploadError(res) {
				this.$modal.msgError('上传失败，请重试');
				this.$modal.closeLoading();
				this.$emit('uploadEnd', 'error');
			},
			// 上传结束处理
			uploadedSuccessfully() {
				if (this.number > 0 && this.uploadList.length === this.number) {
					this.fileList = this.fileList.concat(this.uploadList);
					this.uploadList = [];
					this.number = 0;
					this.$emit('input', this.listToString(this.fileList));
					this.$modal.closeLoading();
				}
			},

			rentContractUrl(url) {
				let that = this;
				this.isTxt = false;
				this.isDoc = false;
				this.isExcel = false;
				if (this.isFile(url)) {
					let fileExtension = url.slice(url.lastIndexOf('.') + 1);
					if (fileExtension == 'pdf' || fileExtension == 'PDF') {
						return url;
					} else if (
						fileExtension == 'txt' ||
						fileExtension == 'TXT'
					) {
						this.isTxt = true;
						downFile(url).then(res => {
							const reader = new FileReader();

							reader.onload = function () {
								that.txtContent = reader.result;
							};
							reader.readAsText(res);
						});
						return url;
					} else if (
						fileExtension == 'doc' ||
						fileExtension == 'docx' ||
						fileExtension == 'DOC' ||
						fileExtension == 'DOCX'
					) {
						this.isDoc = true;
						return url;
					} else if (
						fileExtension == 'xls' ||
						fileExtension == 'xlsx' ||
						fileExtension == 'XLS' ||
						fileExtension == 'XLSX'
					) {
						this.isExcel = true;
						return url;
					} else {
						return this.baseFileUrl + encodeURIComponent(url);
					}
				} else {
					return url;
				}
			},

			// 预览
			handlePictureCardPreview(file) {
				preview({
					url: file.url,
				});
				return;
				let suf = file.fileName?.split('.').at(-1);
				if (this.img.includes(suf)) {
					// 图片
					let url = this.rentContractUrl(file.url);
					this.$imagePreview({
						urlList: [url],
						maskBg: '#fff',
					});
				} else {
					// 文件
					this.srcList = [];
					this.dialogVisible = true;
					this.dialogImageUrl = this.rentContractUrl(file.url);
					this.srcList.push(this.rentContractUrl(file.url));
				}
			},

			//是否能预览
			canOpen(file) {
				let fileExtension = file.url.slice(
					file.url.lastIndexOf('.') + 1,
				);
				return this.unKnowFile.indexOf(fileExtension.toLowerCase()) < 0;
			},

			// 对象转成指定字符串分隔
			listToString(list, separator) {
				let strs = '';
				separator = separator || ',';
				for (let i in list) {
					if (list[i].ossId) {
						strs += list[i].ossId + separator;
					}
				}
				return strs != '' ? strs.substr(0, strs.length - 1) : '';
			},
		},
	};
</script>
<style>
	.uoloadSty .el-upload--picture-card {
		width: 110px;
		height: 110px;
		line-height: 110px;
	}

	.disUoloadSty .el-upload--picture-card {
		display: none; /* 上传按钮隐藏 */
	}
</style>
<style scoped lang="scss">
	::v-deep.hideUpload .el-upload--picture-card {
		display: none;
	}

	::v-deep .el-upload--picture-card {
		width: 104px;
		height: 104px;
		line-height: 104px;
	}

	::v-deep .el-upload-list--picture-card .el-upload-list__item {
		width: 104px;
		height: 104px;
	}

	// 去掉动画效果
	::v-deep .el-list-enter-active,
	::v-deep .el-list-leave-active {
		transition: all 0s;
	}

	::v-deep .el-list-enter,
	.el-list-leave-active {
		opacity: 0;
		transform: translateY(0);
	}

	.component-upload-image {
		margin-right: 15px;
	}

	.hideRight {
		::v-deep .el-upload-list__item-status-label {
			display: none !important;
		}
	}

	.file-name {
		text-align: center;
		font-size: 11px;
		margin: 0;
		word-break: break-all;
		padding: 0 3px;

		.file-name_inline {
			line-height: 1.5;
			margin-top: 3px;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 4;
		}
	}

	.file-wrap {
		width: 100%;
		height: 100%;
		position: relative;
		display: flex;
		flex-direction: column;
		justify-content: center;
		.download_img {
		}
	}

	::v-deep .el-upload-list--picture-card .el-upload-list__item,
	.is-success {
		margin: 0 8px -2px 0 !important;
	}
</style>
